import axios from "axios";
import { BASE_URL } from "./base.js";
import { ElMessage ,ElLoading} from "element-plus"; 
import { validateRes, getResData, isFile } from "./util.js";
import router from "../router/index.js"; 

import { storage } from '@/utils/storage.js';

axios.defaults.baseURL = BASE_URL;

axios.defaults.timeout = 300000;

axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";

// 1. 创建axios实例
const instance = axios.create({
  method: "post",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  },
});

let loading;

// 2.请求拦截
instance.interceptors.request.use(
  (config) => {
    config.headers["authentication"] =storage.get(`be-token`);

    loading = ElLoading.service(
      Object.assign(
        {
          lock: true,
          text: "正在加载...",
          background: "transparent",
        },
        config.loadingPreset || {}
      )
    );

    return config;

  },
  (error) => {
    //  请求发生错误，抛出异常
    Promise.reject(error);
  }
);

// 3.响应拦截
instance.interceptors.response.use(
  (res) => {  
    if (res.headers.authentication){
      storage.set(`be-token`, res.headers.authentication);
    }

    if (res.data && validateRes(res)) { 

      loading && loading.close();
      return isFile(res) ? res : getResData(res.data);
    } else {
      loading && loading.close();
 
      if(res.config && res.config.rejectOnError) {
        return Promise.resolve(res.data);
      }
 
      ElMessage({
        message: res.data.msg,
        type: "warning",
        grouping: true,
        duration: 2000,
      });

      if (
        res.data.code === 1401 &&
        router.currentRoute.value.name !== "login"
      ) {
        router.push("/login");
      }
      return Promise.reject(res.data.msg);
    }
  },
  (err) => {
    loading && loading.close();
 
    ElMessage({
      message: err.message,
      grouping: true,
      type: "warning",
    }); 
  }
);
// 4.导出 axios 实例

export default function ({ url, method, ...config }, data) {

  let sendKey = {
    post: "data",
    get: "params",
  };

  method = method || "post";

  return instance({
    method: method,
    [sendKey[method]]: data,
    url: url,
    ...config,
  });
}
